package com.star.sync.elasticsearch.common;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.LinkedList;
import java.util.List;

/**
 * @author liu
 */
@Component
public class EsSearchUtil {

    public static EsSearchUtil esSearchUtil;


    @Autowired
    RestHighLevelClient restHighLevelClient;

    @PostConstruct
    public void init() {
        esSearchUtil = this;
        esSearchUtil.restHighLevelClient = this.restHighLevelClient;
    }


    public Object search(SearchRequest searchRequest, Class clazz) throws Exception {
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        List<Object> list = new LinkedList<>();
        for (SearchHit hit : searchHits) {
            String sourceAsString = hit.getSourceAsString();
            list.add(JSON.parseObject(sourceAsString, clazz));
        }
        return list.size() >= 1 ? list.get(0) : null;
    }

    public Object get(GetRequest getRequest, Class clazz) throws Exception {
        Object result = null;
        GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        if (getResponse.isExists()) {
            result = JSON.parseObject(getResponse.getSourceAsString(), clazz);
        }
        return result;
    }


}
